package com.xj.datastructure.sort;

import java.util.Random;

/**
 * author: xiajun
 * Date: 2014-07-20
 * Time: 17-00-00
 * 快排分区TopN
 */
public class TopK {
    Random random = new Random();

    public static void main(String[] args) {
        int a[] = {42, 65, 23, 43, 145, 211, 34, 7, 3, 56, 85};
        TopK top = new TopK();
        top.getTopK(a, 3);
        for (int j = 0; j < a.length; j++) {
            System.out.print(a[j] + "  ");
        }
    }

    public void getTopK(int[] a, int k) {
        int start = 0, end = a.length - 1;
        int index = pos2(a, start, end);
        while (index != k - 1) {
            if (index > k - 1) {
                end = index - 1;
                index = pos2(a, start, end);
            } else {
                start = index + 1;
                index = pos2(a, start, end);
            }
        }

    }

    /**
     * 迭代找出最小的topN 并返回N
     *
     * @param a
     * @param start
     * @param end
     * @return
     */
    public int pos(int[] a, int start, int end) {
        int index = start;
        int tmp = a[index];
        a[index] = a[end];
        a[end] = tmp;
        for (int i = start; i < end; i++) {
            if (a[i] <= a[end]) {
                if (index != i) {
                    tmp = a[index];
                    a[index] = a[i];
                    a[i] = tmp;
                }
                index++;
            }
        }
        tmp = a[end];
        a[end] = a[index];
        a[index] = tmp;
        return index;
    }

    public int pos2(int[] a, int start, int end) {
        if(start==end){
            return start;
        }
        int index = start;
        int f = random.nextInt((end-start))+start;
        int flag = a[f];
        a[f]=a[end];
        a[end]=flag;
        for (int i = start; i < end; i++) {
            if (a[i] <= flag) {
                if (i != index) {
                    int tmp = a[i];
                    a[i] = a[index];
                    a[index] = tmp;
                }
                index++;
            }
        }
        a[end] = a[index];
        a[index] = flag;
        return index;
    }
}
